faApp.controller('FaListCtrl',['$scope','faService','$location','$rootScope','$controller','$route','$routeParams','exportService','licaishiManagerService','sessionService','$cookieStore','$cookies',function($scope,faService,$location,$rootScope,$controller,$route,$routeParams,exportService,licaishiManagerService,sessionService,$cookieStore,$cookies) {
  $scope.ctrlName = "FaListCtrl";
  $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.fas = [];
  $scope.black = {blackType:1};
  $scope.vtype="";
  if($routeParams.orderFlag=="1"&&$routeParams.notHasVisit){
    $scope.vtype="成交客户列表";
  }else if($routeParams.orderFlag=="2"&&$routeParams.notHasVisit){
    $scope.vtype="待沉寂理财师列表";
  }else if($routeParams.notHasVisit){
    $scope.vtype="待回访理财师列表";
  }else if($routeParams.notHasCheck){
    $scope.vtype="待审核理财师列表";
  }else if($routeParams.isnoManagerUserLicaishi){
    $scope.vtype="待分配理财师列表";
  }else{
    $scope.vtype="所有理财师列表";
  }

  if($routeParams.newPage){
    console.info($routeParams.isEmptyParam)
    if($routeParams.isEmptyParam){
        $scope.searchMap={isnoManagerUserLicaishi:"",notHasVisit:""
        ,notHasCheck:"",orderFlag:"",systemUserId:"",visitModel:"",systemUserId2:"",
          "pageSize" : 20,   "pageNo" : 1
       };
       $scope.config={isnoManagerUserLicaishi:"",notHasVisit:""
        ,notHasCheck:"",orderFlag:"",systemUserId:"",visitModel:"",
            "pageSize" : 20,   "pageNo" : 1
       };
    }
    $scope.listWhere="";
    if($routeParams.isnoManagerUserLicaishi){//待分配
      $scope.searchMap.isnoManagerUserLicaishi=$routeParams.isnoManagerUserLicaishi;
      $scope.config.isnoManagerUserLicaishi=$routeParams.isnoManagerUserLicaishi;
      $scope.listWhere=$scope.listWhere+"&isnoManagerUserLicaishi="+$routeParams.isnoManagerUserLicaishi;
    }
    if($routeParams.notHasVisit){//是否回访
      $scope.searchMap.notHasVisit=$routeParams.notHasVisit;
      $scope.config.notHasVisit=$routeParams.notHasVisit;
      $scope.listWhere=$scope.listWhere+"&notHasVisit="+$routeParams.notHasVisit;
    }
    if($routeParams.notHasCheck){//待审核
      $scope.searchMap.notHasCheck=$routeParams.notHasCheck;
      $scope.config.notHasCheck=$routeParams.notHasCheck;
       $scope.listWhere=$scope.listWhere+"&notHasCheck="+$routeParams.notHasCheck;
    }
    if($routeParams.orderFlag){//是否交易    1 成交客户
      $scope.searchMap.orderFlag=$routeParams.orderFlag;
      $scope.config.orderFlag=$routeParams.orderFlag;
      $scope.config.showOrderFlag=true;
      $scope.listWhere=$scope.listWhere+"&orderFlag="+$routeParams.orderFlag;
    }
    console.info($routeParams.systemUserId)
    if($routeParams.systemUserId){//当前用户ID  我的客户列表
      $scope.searchMap.systemUserId=$routeParams.systemUserId;
      $scope.config.systemUserId=$routeParams.systemUserId;
      //$scope.searchMap.systemUserId2=$routeParams.systemUserId;
      $scope.config.showSystemUser=true;
      $scope.listWhere=$scope.listWhere+"&systemUserId="+$routeParams.systemUserId;
    }
    if($routeParams.pageNo){//当前用户ID  我的客户列表
      $scope.searchMap.pageNo=$routeParams.pageNo;
      $scope.config.pageNo=$routeParams.pageNo-0;
    }

    if(($routeParams.orderFlag==2&&$routeParams.notHasVisit)||$routeParams.orderFlag==1){
      $scope.showVisit=true;
      if($routeParams.orderFlag==2&&$routeParams.notHasVisit){
         $scope.showVisitWhere=true;
      }else{
        $scope.showVisitWhere=false;
      }
    }
  }

  $scope.config1={"pageSize" : 10000};
  var sss={"userId":"*","username":"*无服务顾问*"};
  if(!$scope.config.showSystemUser){

    licaishiManagerService.list($scope.config1).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.licaishiManagerUserList = json.list;
          $scope.licaishiManagerUserList.push(sss);
          $scope.loading = false;
        }
      });


  }else{
    licaishiManagerService.otherList($scope.config1).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.licaishiManagerUserList = json.list;
        $scope.licaishiManagerUserList.push(sss);
        $scope.loading = false;
      }
    });
  }



  $scope.chkAllLicaishiList = function(){
    if($("#chkAllLicaishiList").attr("checked") == "checked"){
      $("[name='chkLicaishiList']").attr("checked","checked");
    }else{
      $("[name='chkLicaishiList']").attr("checked",false);
    }
  }

  $scope.licaishiManage = function(t){
    chooseLicaishiList(t);
    if($scope.chooseLicaishiId != undefined && $scope.chooseLicaishiId != ""){
      $scope.chooseLicaishiIdCount = $scope.chooseLicaishiId.split(",").length - 1;
      $scope.isShowLicaishiManagerLayer = true;
    }else{
      alert("请选择理财师！");
      return;
    }
    if(t != undefined && t != "" && t == "1"){
      licaishiManagerService.list({"pageSize":9999,"pageNo":1}).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.licaishiManagerUserList2 = json.list;
        }
      });
    }
    $scope.t = t;
  };
  chooseLicaishiList = function(t){
    $scope.chooseLicaishiId = "";
    $scope.omu = "";
    $("[name='chkLicaishiList']").each(function(i){
      if($(this).attr("checked") == "checked"){
        //if(t == 1 && $(this).attr("omu")){
        //  alert("请选择未分配的理财师！");
        //  $scope.chooseLicaishiId = -1;
        //  return false;
        //}else
        if(t == 0 && !$(this).attr("omu")){
          alert("请选择已分配的理财师！");
          $scope.chooseLicaishiId = -2;
          return false;
        }
        if($(this).attr("value") != undefined && $(this).attr("value") != ""){
          $scope.chooseLicaishiId += $(this).attr("value") + ",";
          $scope.omu += $(this).attr("omu") + ",";
        }
      }
    });
  };
  $scope.managerLicaishi = {};
  $scope.loading=false;
  $scope.fenpeiOrHuishou = function(t){
    
    if($scope.chooseLicaishiId!=null&&$scope.chooseLicaishiId!=undefined){
      $scope.managerLicaishi.licaishiIds=$scope.chooseLicaishiId.substring(0, $scope.chooseLicaishiId.length - 1);
    }
    if(t == "1"){
      if($scope.managerLicaishi.systemUserId != undefined && $scope.managerLicaishi.systemUserId != "" && t != ""){
       //关闭分配按钮
        $scope.loading=true;
        $scope.isShowLicaishiManagerLayer=false;
        // 分配操作
        licaishiManagerService.managerLicaishiUserAdd($scope.managerLicaishi).then(function(json){
         //放开分配按钮
           $scope.loading=false;
          if (json.statusCode){
               alert("出错了:" + json.statusCode);
          }else{
            // 操作成功！分配成功！
            var _map = json.map;
            if(_map.not_aCount>0){
              alert('A类分配超出上限，失败'+_map.not_aCount);
            }else if(_map.not_okCount>0){
              alert('OK类分配超出上限，失败'+_map.not_okCount);
            }else {
              $scope.alertNextPage("分配成功！");
            }
            $route.reload();
          }
        },function(res){
          alert('网络状态不稳定或超时！');
        });
      }else{
        alert("请选择服务顾问！");
      }
    }else if(t == '0'){
      var tmpid = "";
      angular.forEach($scope.omu.split(","),function(o,i){
        if(i == 0){
          tmpid = o;
        }else{
          if(o != undefined && o != "" && o != tmpid){
            tmpid = "-99";
          }
        }
      });
      if(tmpid != undefined && tmpid != "-99"){
        //关闭分配按钮
        $scope.loading=true;
        $scope.isShowLicaishiManagerLayer=false;
        // 回收时，理财师服务顾问设为空
        $scope.managerLicaishi.systemUserId = "";
        // 回收
        licaishiManagerService.huishouManagerLicaishiByUser($scope.managerLicaishi).then(function(json){
         //放开分配按钮
            $scope.loading=false;
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $scope.alertNextPage("回收成功！");
            $route.reload();
          }
        });
      }else{
        if(confirm("选择了多个理财师，且服务顾问人不同，确认要同时回收吗！")){
          //关闭分配按钮
            $scope.loading=true;
          $scope.isShowLicaishiManagerLayer=false;
          // 回收时，服务理财师设为空
          $scope.managerLicaishi.systemUserId = "";
          // 回收
          licaishiManagerService.huishouManagerLicaishiByUser($scope.managerLicaishi).then(function(json){
             //放开分配按钮
            $scope.loading=false;
            if(json.statusCode== "4002"){
              alert("存在已分配理财师，请先收回，后分配！");
            }else if (json.statusCode){
              alert("出错了:" + json.statusCode);
            }else{
              $scope.alertNextPage("回收成功！");
              $route.reload();
            }
          });
        }
      }
    }

  }
  $scope.config['orderBy'] = $routeParams.orderBy || '',
  $scope.config['orderByTag'] = $routeParams.orderByTag || '',

  $rootScope.viewNextBtn = {
    listWhere : $scope.listWhere

  }
  console.log($scope.config)
  $scope.$watch('config',function(){
    console.log('config-up');
    if ($scope.watchIsChange()){
      $scope.loading=true;
      faService.faList($scope.config).then(function(json){
        $scope.fas = json.list || [];
        $scope.pager = json.pager;
        $rootScope.myKeHuNowPageListSize = json.list || [];
        $rootScope.viewNextBtn.pageNo = $scope.pager.pageNo;
        var arr = [];
        for(t in json.list){
          arr.push(json.list[t].id);
        }
        $scope.loading=false;
        $cookies.myKeHuNowPageListSize = angular.toJson(arr);
      });
    }
  },true);
  //读取查询 seeionStronge
  $scope.getLastSearchConfig();
  // $scope.search();

  $scope.orderbyPositionMap = {};
  if (!$routeParams.orderBy && !$routeParams.orderByTag){
    $scope.orderbyPositionMap['weight'] = "0";
  }else{
    $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
  }
  $scope.orderbyFreqMap = {
    "createDate":["desc","asc"],
    "lastLoginTime":["desc","asc"],
    "latestVisitTime":["desc","asc"],
    "addAuthDate":["desc","asc"]
  };
  $scope.orderby = function(field){
    var freq = $scope.orderbyFreqMap[field];
    var old = $scope.orderbyPositionMap[field];
    $scope.orderbyPositionMap = {};
    
    if (old == undefined){
      $scope.orderbyPositionMap[field] = 0;
    }else{
      $scope.orderbyPositionMap[field] = old + 1;
      if ($scope.orderbyPositionMap[field] >= freq.length){
        $scope.orderbyPositionMap[field] = 0;
      }
    }
    
    if (field == "weight"){
      $scope.config.orderBy = "";
      $scope.config.orderByTag = "";
    }else{
      $scope.config.orderBy = field;
      $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
    }
  }

  $scope.toViewPage = function(id){
    var url = 'fa/view?id=' + id + $scope.listWhere + '&pageNo=' + $scope.config.pageNo;
    $location.url(url);
  }

  $scope.showBlackAddForm = function(id){
    $scope.black.userId = id;
    $scope.showBlackAddFormFlag = true;
  };

  $scope.blackAdd = function(){
    if (!$scope.form.$invalid){
      faService.blackAdd($scope.black).then(function(json){
        if (!json.statusCode){
          $scope.addAlert("操作成功");
          $route.reload();
        }else{
          alert("出错了:" + json.statusCode);
        }  
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };

  $scope.cert = {id:""};
  $scope.showCertForm = function(id){
    $scope.cert.id = id;
    $scope.showCertFormFlag = true;
    
  };
  $scope.certSave = function(){
    if (!$scope.certform.$invalid){
      if ($scope.cert.type && $scope.cert.uRole != "99"){
        $scope.cert.uRole = $scope.cert.type;
      }
      if (!$scope.cert.uRole || ($scope.cert.uRole == "2" && (!$scope.cert.type))){
        alert("请选择评级");
        return;
      }
      faService.certSave($scope.cert).then(function(json){
        if (!json.statusCode){
          $scope.addAlert("操作成功");
          $route.reload();
        }else{
          alert("出错了:" + json.statusCode);
        }  
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };
  
  $scope.selectLevelType = function(type){
    $scope.cert.type = type;
    $scope.cert.uRole = "2";
  };
  
  $scope.selectRoleResult = function(){
    if ($scope.cert.uRole == "99"){
      $scope.cert.type = "";
    }
  }
  
  $scope.export = function(){
    exportService.exportCSV($scope.config,"FA_LIST_EXPORT");
  };


  $scope.setPageSize = $scope.config.pageSize;

  $scope.changePageSize = function(){
    if(!$scope.setPageSize){
      alert('不为空且最大不超过1000');
      $scope.setPageSize = $scope.config.pageSize;
    }else{
      $scope.config.pageSize = $scope.setPageSize;
    }
  };
  if ($scope.dictMap.roleMapModel[0].value != 'Y') $scope.dictMap.roleMapModel.unshift({value:"Y",text:"认证已通过"});
  console.info('注册来源活动');
  function getactSource(){
    faService.queryActSource().then(function(json){
        console.info(json);
        $scope.actSourceList = json.list;
    });
  }
  getactSource();


}]);

faApp.controller('FaAddCtrl',['$scope','faService','$location','$controller',function($scope,faService,$location,$controller) {   
  $controller('BaseCtrl', {$scope: $scope}); 
}]);

faApp.controller('FaViewCtrl',['$rootScope','$scope','faService','$location','$controller','$routeParams','$route','$cookies','$timeout','$filter',function($rootScope,$scope,faService,$location,$controller,$routeParams,$route,$cookies,$timeout,$filter) {

  $controller('BaseCtrl', {$scope: $scope});

  $scope.id = $routeParams.id;
  $scope.item = {};
  $scope.visit = {};
  $scope.loading = true;
  $scope.auditOptionMessage = "";
  $scope.aoMsg = false;
  $scope.firstReturnVisitCycle = "";
  $scope.stayAwayFromTheLastVisit = "";

  var myKeHuNow = angular.fromJson($cookies.myKeHuNowPageListSize);

  $scope.listWhere="?newPage=true";
  $scope.vtype="";
  if($routeParams.orderFlag=="1"&&$routeParams.notHasVisit){
    $scope.vtype="成交客户列表";
  }else if($routeParams.orderFlag=="2"&&$routeParams.notHasVisit){
    $scope.vtype="待沉寂理财师列表";
  }else if($routeParams.notHasVisit){
     $scope.vtype="待回访理财师列表";
  }else if($routeParams.notHasCheck){
     $scope.vtype="待审核理财师列表";
  }else if($routeParams.isnoManagerUserLicaishi){
     $scope.vtype="待分配理财师列表";
  }else{
    $scope.vtype="所有理财师列表";
  }
  if($routeParams.isnoManagerUserLicaishi){//待分配
    $scope.listWhere=$scope.listWhere+"&isnoManagerUserLicaishi="+$routeParams.isnoManagerUserLicaishi;
  }
  if($routeParams.notHasVisit){//是否回访
    $scope.listWhere=$scope.listWhere+"&notHasVisit="+$routeParams.notHasVisit;
  }
  if($routeParams.notHasCheck){//待审核
    $scope.listWhere=$scope.listWhere+"&notHasCheck="+$routeParams.notHasCheck;
  }
  if($routeParams.orderFlag){//是否交易    1 成交客户
    $scope.listWhere=$scope.listWhere+"&orderFlag="+$routeParams.orderFlag;
  }
  if($routeParams.systemUserId){//当前用户ID  我的客户列表
    $scope.listWhere=$scope.listWhere+"&systemUserId="+$routeParams.systemUserId;
  }
  if($routeParams.pageNo){//当前用户ID  我的客户列表
    $scope.listWhere=$scope.listWhere+"&pageNo="+$routeParams.pageNo;
  }
  $scope.$watch('id',function(){
    for(m in myKeHuNow){
      if( myKeHuNow[m] == $scope.id ){
        $scope.now = m;
      }
    }
    faService.faQuery({id:$scope.id}).then(function(json){
      $scope.item = json.faUserInfo || {};
      $scope.loading = false;
      /**基本 属性**/
      if($scope.item.sourceCode =="")  $scope.item.sourceCode="--";
      if($scope.item.sourceLoginName =="")  $scope.item.uManagerId="--";
      // $scope.item.uManagerId = $scope.item.uManagerId=0 || "--";
      if($scope.item.uManagerId==0) $scope.item.uManagerId="--";


      /**审核 属性**/
      $scope.cert.uCompanyName = $scope.item.uCompanyName || "";
      $scope.cert.uCompanyADD = $scope.item.uCompanyADD || "";
      $scope.cert.uJob = $scope.item.uJob || "";
      $scope.cert.uRole = $scope.item.uRole ;
      $scope.cert.type = $scope.cert.uRole;
      $scope.cert.uRealName = $scope.item.uRealName || "";
      if($scope.item.faUserauth){
        $scope.cert.wechatNo = $scope.item.faUserauth.wechatNo || "";
      }
      if($scope.item.uRole!="99"){
        $scope.cert.uRole ="2";
      }
      $scope.cert.uAuditOpinion=$scope.item.uAuditOpinion ;
      if($scope.item.uRole=="99"&&$scope.cert.uAuditOpinion!="注册手机号码与名片手机号码不一致"&&$scope.cert.uAuditOpinion!="未上传名片或上传名片与资质要求不符"){
        $scope.auditop.auditOptionMessage=$scope.cert.uAuditOpinion;
        $scope.cert.uAuditOpinion="3";
        $scope.aoMsg=true;
      }
      $scope.cert.uSex = $scope.item.uSex;
      $scope.cert.uEmail = $scope.item.uEmail || "";
      $scope.cert.auditRemarks = $scope.item.auditRemarks || "";

      /**回访 属性**/
      $scope.visit.faId = $scope.item.id;
      $scope.visit.id = $scope.item.id;
      $scope.visit.uRealName = $scope.item.uRealName || "";
      $scope.visit.uMobile = $scope.item.uMobile || "";

      $scope.visit.uCompanyName = $scope.item.uCompanyName || "";
      $scope.visit.uAddress = $scope.item.uAddress || "";
      $scope.visit.uJob = $scope.item.uJob || "";
      $scope.visit.uEmail = $scope.item.uEmail || "";
      $scope.visit.uSex = $scope.item.uSex;


      if($scope.item.faUserauth){
        $scope.visit.otherContactInfo = $scope.item.faUserauth.otherContactInfo || "";
        $scope.visit.wechatNo = $scope.item.faUserauth.wechatNo || "";
        $scope.visit.customerHeat = $scope.item.faUserauth.customerHeat || "";
        $scope.visit.customerCategory = $scope.item.faUserauth.customerCategory || "";
        $scope.visit.customerStage = $scope.item.faUserauth.customerStage || "";
        $scope.visit.customerKnowledge = $scope.item.faUserauth.customerKnowledge || "";
        $scope.visit.customerSource = $scope.item.faUserauth.customerSource || "";
        $scope.visit.customerLable = $scope.item.faUserauth.customerLable || "";
        $scope.visit.customerCategory = $scope.item.faUserauth.customerCategory || "";
      }
      $scope.firstReturnVisitCycle = diffTime($scope.item.licaishiVO.createDate,$scope.item.visitStatisticVO.firstReturnVisitTime);
      $scope.stayAwayFromTheLastVisit = diffTime($scope.item.visitStatisticVO.latestVisitTime,$scope.item.visitStatisticVO.systemDate);
      // $scope.selectLevelType($scope.cert.uRole);
    });

    faService.faUserVisit($scope.id).then(function(json){
      $scope.visitList = json.list;
    });
  },true)
  //faService.faQuery({id:$scope.id}).then(function(json){
  //  $scope.item = json.faUserInfo || {};
  //  $scope.loading = false;
  //  /**基本 属性**/
  //  if($scope.item.sourceCode =="")  $scope.item.sourceCode="--";
  // if($scope.item.sourceLoginName =="")  $scope.item.uManagerId="--";
  // // $scope.item.uManagerId = $scope.item.uManagerId=0 || "--";
  // if($scope.item.uManagerId==0) $scope.item.uManagerId="--";
  //
  //
  //  /**审核 属性**/
  //  $scope.cert.uCompanyName = $scope.item.uCompanyName || "";
  //  $scope.cert.uCompanyADD = $scope.item.uCompanyADD || "";
  //  $scope.cert.uJob = $scope.item.uJob || "";
  //  $scope.cert.uRole = $scope.item.uRole ;
  //  $scope.cert.type = $scope.cert.uRole;
  //  $scope.cert.uRealName = $scope.item.uRealName || "";
  //  if($scope.item.faUserauth){
  //    $scope.cert.wechatNo = $scope.item.faUserauth.wechatNo || "";
  //  }
  //  if($scope.item.uRole!="99"){
  //    $scope.cert.uRole ="2";
  //  }
  //   $scope.cert.uAuditOpinion=$scope.item.uAuditOpinion ;
  //  if($scope.item.uRole=="99"&&$scope.cert.uAuditOpinion!="注册手机号码与名片手机号码不一致"&&$scope.cert.uAuditOpinion!="未上传名片或上传名片与资质要求不符"){
  //    $scope.auditop.auditOptionMessage=$scope.cert.uAuditOpinion;
  //    $scope.cert.uAuditOpinion="3";
  //    $scope.aoMsg=true;
  //  }
  //  $scope.cert.uSex = $scope.item.uSex;
  //  $scope.cert.uEmail = $scope.item.uEmail || "";
  //  $scope.cert.auditRemarks = $scope.item.auditRemarks || "";
  //
  //  /**回访 属性**/
  //  $scope.visit.faId = $scope.item.id;
  //  $scope.visit.id = $scope.item.id;
  //  $scope.visit.uRealName = $scope.item.uRealName || "";
  //  $scope.visit.uMobile = $scope.item.uMobile || "";
  //
  //  $scope.visit.uCompanyName = $scope.item.uCompanyName || "";
  //  $scope.visit.uAddress = $scope.item.uAddress || "";
  //  $scope.visit.uJob = $scope.item.uJob || "";
  //  $scope.visit.uEmail = $scope.item.uEmail || "";
  //  $scope.visit.uSex = $scope.item.uSex;
  //
  //
  //  if($scope.item.faUserauth){
  //      $scope.visit.otherContactInfo = $scope.item.faUserauth.otherContactInfo || "";
  //      $scope.visit.wechatNo = $scope.item.faUserauth.wechatNo || "";
  //      $scope.visit.customerHeat = $scope.item.faUserauth.customerHeat || "";
  //      $scope.visit.customerCategory = $scope.item.faUserauth.customerCategory || "";
  //      $scope.visit.customerStage = $scope.item.faUserauth.customerStage || "";
  //      $scope.visit.customerKnowledge = $scope.item.faUserauth.customerKnowledge || "";
  //      $scope.visit.customerSource = $scope.item.faUserauth.customerSource || "";
  //      $scope.visit.customerLable = $scope.item.faUserauth.customerLable || "";
  //      $scope.visit.customerCategory = $scope.item.faUserauth.customerCategory || "";
  //  }
  //  $scope.firstReturnVisitCycle = diffTime($scope.item.licaishiVO.createDate,$scope.item.visitStatisticVO.firstReturnVisitTime);
  //  $scope.stayAwayFromTheLastVisit = diffTime($scope.item.visitStatisticVO.latestVisitTime,$scope.item.visitStatisticVO.systemDate);
  //  // $scope.selectLevelType($scope.cert.uRole);
  //});

  $scope.isShowVisitLayer = false;
  $scope.isShowCheckFaUser = false;
  $scope.visitList = [];



  /**回访**/
  $scope.showVisitLayer = function(id,mobile,mediaSource,isValid){
    faService.faUserVisit($scope.id).then(function(json){
      $scope.visitList = json.list;
    });
    $scope.isShowVisitLayer = true;
  }
  /**审核**/
  $scope.checkFaUser = function(id,mobile,mediaSource,isValid){

    $scope.isShowCheckFaUser = true;
  }
  //下一页上一页

  $scope.faItem = function (f) {
    for(m in myKeHuNow){
      if( myKeHuNow[m] == $scope.id ){
        $scope.now = m;
      }
    }
    if(f == 'next'){
      $scope.id = myKeHuNow[$scope.now-0+1];

    }else if(f == 'prev') {
      $scope.id = myKeHuNow[$scope.now-1];
    }
    $location.url("/fa/view?id="+$scope.id+$rootScope.viewNextBtn.listWhere+'&pageNo='+$rootScope.viewNextBtn.pageNo);
  }
  // 动态显示三方公司
  $scope.sfCompanyList = {};
  $scope.isShowSelectCompany = false;
  $scope.isNewCompany = false;
  $scope.newCompanyName = '';

  $scope.showSanfangCompany = function(name){
    $scope.isNewCompany = false;
    if(name){
      // 根据name查询列表
      if(name.length >= 2){
        faService.sanfangQuery({keyWord: name}).then(function(json){
          $scope.sfCompanyList = json.list;
          if(json && $scope.sfCompanyList.length <= 0){
            $scope.isNewCompany = true;
            $scope.newCompanyName = name;
            $scope.isShowSelectCompany = false;
          }else{
             $scope.isShowSelectCompany = true;
          }
        });
      }
    }else{
      $scope.isShowSelectCompany = false;
    }
  }
  $scope.selectedSanfangCompany = function(name, t){
    $scope.isShowSelectCompany = false;
    if(t){
      $scope.visit.uCompanyName = name;
    }else{
      $scope.cert.uCompanyName = name;
    }
  }

  $scope.addFaUserVisit = function(){
    if ($scope.visitform.$invalid){
       alert("请先完整填写信息");
      return;
    }

    /**先提交 基本信息**/
    faService.faUserVisitDetailAdd($scope.visit).then(function(json){
      if (!json.statusCode){
        if($scope.isNewCompany && $scope.newCompanyName){
          faService.sanfangAdd({tpcFullName: $scope.newCompanyName}).then(function(json){
            console.log(json);
          });
        }

        $scope.addAlert("操作成功");
        //$route.reload();
        $location.path('fa/view').search({id:$scope.id})
      }else{
        alert("出错了:" + json.statusCode);
      }
    });

    /**再提交 回访信息**/
    faService.faUserVisitAdd({faId : $scope.id, remark : $scope.visitRemark}).then(function(json){
      if (!json.statusCode){
        faService.faUserVisit($scope.id).then(function(json){

          $scope.visitList = json.list;
        });
        $scope.visitRemark = "";
      }else{
        alert("出错了:" + json.statusCode);
      }
    });
  }

  $scope.faUserVisitUpdate = function(a){
    if(a != undefined && a != ""){
      faService.faUserVisitUpdate({faId : $scope.id, adValid : a}).then(function(json){
        if (!json.statusCode){
          alert("修改成功！");
        }else{
          alert("出错了:" + json.statusCode);
        }
      });
    }else{
      alert("请选择有效性！");
    }
  }

  $scope.black = {blackType:1};
  $scope.showBlackAddForm = function(){
    $scope.black.userId = $scope.id;
    $scope.showBlackAddFormFlag = true;
  };

  $scope.blackAdd = function(){
    if (!$scope.form.$invalid){
      faService.blackAdd($scope.black).then(function(json){
        if (!json.statusCode){
          $scope.alertNextPage("操作成功");
          $location.path("/fa/list");
        }else{
          alert("出错了:" + json.statusCode);
        }
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };
  diffTime = function (startDate,endDate) {
    var diff=endDate - startDate;//时间差的毫秒数
    if(startDate==null || endDate ==null ||diff <0){
      return "--";
    }

    //计算出相差天数
    var days=Math.floor(diff/(24*3600*1000));

    //计算出小时数
    var leave1=diff%(24*3600*1000);    //计算天数后剩余的毫秒数
    var hours=Math.floor(leave1/(3600*1000));
    //计算相差分钟数
    var leave2=leave1%(3600*1000);        //计算小时数后剩余的毫秒数
    var minutes=Math.floor(leave2/(60*1000));

    //计算相差秒数
    var leave3=leave2%(60*1000);      //计算分钟数后剩余的毫秒数
    var seconds=Math.round(leave3/1000);

    var returnStr = seconds + "秒";
    if(minutes>0) {
      returnStr = minutes + "分" + returnStr;
    }
    if(hours>0) {
      returnStr = hours + "小时" + returnStr;
    }
    if(days>0) {
      returnStr = days + "天" + returnStr;
    }
    return returnStr;
  }

  $scope.cert = {};
  $scope.auditop={};
  $scope.certSave = function(){
    $scope.cert.id = $scope.id

    if (!$scope.certform.$invalid){
      if ($scope.cert.type && $scope.cert.uRole != "99" && $scope.cert.uRole != "98"){
        $scope.cert.uRole = $scope.cert.type;
      }
      if (!$scope.cert.uRole || ($scope.cert.uRole == "2" && (!$scope.cert.type||$scope.cert.type=='98'))){
        alert("请选择评级");
        return;
      }
      if($scope.aoMsg&&$scope.cert.uRole == 99){
        if(!$scope.auditop.auditOptionMessage){
          alert("请填写未通过原因！");
          return;
        }
        $scope.cert.uAuditOpinion = $scope.auditop.auditOptionMessage;
      }

      faService.certSave($scope.cert).then(function(json){
        if (!json.statusCode){
          if($scope.isNewCompany && $scope.newCompanyName){
            faService.sanfangAdd({tpcFullName: $scope.newCompanyName}).then(function(json){
              console.log(json);
            });
          }

          $scope.addAlert("操作成功");
          $route.reload();
          //$location.url("/fa/view?id="+$scope.id);
          //$route.reload();

        }else{
          alert("出错了:" + json.statusCode);
        }
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };

  $scope.selectLevelType = function(type){
    $scope.cert.type = type;
    $scope.cert.uRole = "2";
  };
  $scope.selectCustomerLable = function(type){
    $scope.visit.customerLable = type;
  };
  $scope.selectRoleResult = function(){
    if ($scope.cert.uRole == "99"){
      $scope.cert.type = "1";
      $scope.cert.uAuditOpinion="";
    }else{
      $scope.cert.type = "";

    }
  };

  $scope.auditOption = function(){
    if($scope.cert.uAuditOpinion == "3"){
      $scope.aoMsg = true;
    }else{
      $scope.aoMsg = false;
    }
  };

  $scope.isShowSaveUpload = false;
  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.item.uCardAddress = response.attribute.fileUrl;
        $scope.isShowSaveUpload = true;
        $scope.$apply();
      } else {
        alert('上传失败');
      }
    }
  });

  $scope.saveUpload = function(){
    if (!$scope.item.uCardAddress){
      alert("请先上传图片");
      return;
    }
    delete $scope.item.lastLoginTime;
    faService.certSaveImg($scope.item).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        alert("保存成功");
        $scope.cert.uRole="98";
      }
    });
  };

  $scope.companyInvitationCode = "";
  $scope.markFaUser = function(){
    if($scope.id){
      faService.markFaUser($scope.id).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.companyInvitationCode = json.cic;
          alert("标记成功！");
        }
      });
    }else{
      alert("系统异常，请刷新页面重试！");
    }
  }
  //待办和发送短信
  console.info('待办和发送短信');
  $scope.sendMsgData = {};
  $scope.sendMessage = function(){
    //faRevisitType;//类型1发送短信2待办
    if($scope.sendMsgData.faRevisitType == 1){
      $scope.sendMsgData.faRevisitDate = undefined;
    }else {
      $scope.sendMsgData.faRevisitPhone = undefined;
      $scope.sendMsgData.faRevisitDate = $filter("date")($scope.sendMsgData.faRevisitDate,"yyyy-MM-dd HH:mm");
    }
    ////关联理财师id
    $scope.sendMsgData.faRevisitUserId =  $scope.item.id;
    var codeMap = {
      '2002':'参数缺失',
      '4013':'时间要大于当前时间'
    };
    faService.revisiitTask($scope.sendMsgData).then(function(json){
        console.log(json);
        if (json.statusCode){
          alert("操作失败:" + codeMap[json.statusCode]);
        }else{
          $scope.sendMsgData.faRevisitContent = '';
          $scope.isShowMsgVariable = false;
          alert("操作成功！");


        }

    });
  };

  $scope.ckSendMessage  = function(type){
    $scope.isShowMsgVariable = true;
    $scope.sendMsgData.faRevisitType = type;

  }


}]);

faApp.controller('FaBlackListCtrl',['$scope','faService','$location','$controller',function($scope,faService,$location,$controller) {
  $controller('BaseCtrl', {$scope: $scope});
  $scope.blacks = {};

  $scope.$watch('config',function(){
    faService.blackList($scope.config).then(function(json){
      $scope.blacks = json.list || [];
      $scope.pager = json.pager;
    });
  },true);

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1,
    "loginName" : '',
  };

  $scope.searchMap = {
    "loginName" : '',
  };

  $scope.search = function(){

    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

  };

  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  };

}]);

faApp.controller('FaBlackViewCtrl',['$scope','faService','$location','$controller','$routeParams','$window',function($scope,faService,$location,$controller,$routeParams,$window) {   
  $controller('BaseCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;
  $scope.black = {blackType:2,userId:$scope.id};
  $scope.detail = {};
  $scope.blackHistorys = [];
  $scope.whiteHistorys = [];

  $scope.showDeleteForm = function(){
    $scope.showDeleteFormFlag = true;
    $window.scrollTo(0,0);
  };

  faService.blackQuery($scope.id).then(function(json){
    $scope.detail = json.dto;
    angular.forEach(json.list,function(o){
      if (o.blackType == "1")$scope.blackHistorys.push(o); 
      else $scope.whiteHistorys.push(o);
    });
  });

  $scope.blackDelete = function(){
    if (!$scope.form.$invalid){
      faService.blackAdd($scope.black).then(function(json){
        if (!json.statusCode){
          $scope.alertNextPage("移除操作成功");
          $location.path("/fa/blacklist");
        }else{
          alert("出错了:" + json.statusCode);
        }  
      });
    }else{
      alert("请先完整填写信息");
      return;
    }
  };
}]);

faApp.controller('FaSbdstatCtrl',['$scope','faService','$location','$controller','$route','exportService','$routeParams',function($scope,faService,$location,$controller,$route,exportService,$routeParams) {   
  $scope.ctrlName = "FaSbdstatCtrl";
  $controller('BaseListCtrl', {$scope: $scope}); 
  $scope.fas = [];

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      faService.sbdstat($scope.config).then(function(json){
        $scope.fas = json.list || [];
        $scope.pager = json.pager;
      });
    }
  },true); 
 
  $scope.export = function(){
    exportService.exportCSV($scope.config,"FA_SBD_EXPORT");
  }; 
 

  $scope.orderbyPositionMap = {};
  if (!$routeParams.orderBy && !$routeParams.orderByTag){
    $scope.orderbyPositionMap['createDate'] = "0";
  }else{
    $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
  }
  $scope.orderbyFreqMap = {"authPassCount":["desc","asc"],"createDate":["desc"]};

  $scope.orderby = function(field){
    var freq = $scope.orderbyFreqMap[field];
    var old = $scope.orderbyPositionMap[field];
    $scope.orderbyPositionMap = {};
    if (old == undefined){
      $scope.orderbyPositionMap[field] = 0;
    }else{
      $scope.orderbyPositionMap[field] = old + 1;
      if ($scope.orderbyPositionMap[field] >= freq.length){
        $scope.orderbyPositionMap[field] = 0;
      }
    }
    if (field == "weight"){
      $scope.config.orderBy = "";
      $scope.config.orderByTag = "";
    }else{
      $scope.config.orderBy = field;
      $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
    }
  }; 
}]);

faApp.controller('FaSbdDetailCtrl',['$scope','faService','$location','$controller','$route','$routeParams',function($scope,faService,$location,$controller,$route,$routeParams) {   
  $controller('BaseCtrl', {$scope: $scope}); 
  $scope.fas = [];

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      faService.sbddetail($scope.config).then(function(json){
        $scope.fas = json.list || [];
        $scope.pager = json.pager;
      });
    }
  },true);

  $scope.config = {
    "pageSize" : 100,
    "pageNo" : 1,
    "uLoginName" : '',
    "sourceCode" : $routeParams.id
  };

  $scope.searchMap = {};

  $scope.search = function(){

    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });
    
    $scope.config.pageNo = 1;

  };
  
  $scope.pageChanged = function(){
    $scope.config.pageNo = $scope.pager.pageNo;
  };  
  
}]);

faApp.controller('SanFangCtrl', ['$scope','faService','$location','$controller','$route','exportService','$routeParams', function($scope,faService,$location,$controller,$route,exportService,$routeParams) {
  $controller('BaseListCtrl', {$scope: $scope});

  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };

  $scope.$watch('config',function(){
    if ($scope.watchIsChange()){
      faService.sanfangQuery($scope.config).then(function(json){
        $scope.list = json.list || [];
        $scope.pager = json.pager;
      });
    }
  },true);

  $scope.sfDelete = function(id){
    if(id){
      if(confirm('确认要删除吗！')){
        faService.sanfangDelete(id).then(function(json){
          $route.reload();
        });
      }
    }else{
      alert('有问题，请刷新页面重试！');
    }
  }

  $scope.isShowUpdateLayer = false;
  $scope.sf = {};


  $scope.toUpdate = function(id){

    if(id){
      $scope.tpcCommoyType = {};
      $scope.isShowUpdateLayer = true;
      $scope.sf.id = id;

      angular.forEach($scope.list, function(o){
        if(o.id == id){
          $scope.sf.tpcFullName = o.tpcFullName;
          $scope.sf.tpcAbbrLetter = o.tpcAbbrLetter;
          $scope.sf.tpcShortName = o.tpcShortName;
          if(o.tpcCompanyProperty!=undefined){
            angular.forEach(o.tpcCompanyProperty.split(","),function(i){
              $scope.tpcCommoyType[i] = true;
            });
          }
        }
      });
    }else{
      alert('有问题，请刷新页面重试！');
    }
  }

  $scope.sfUpdate = function(){
    if($scope.sf){
      if(!$scope.sf.id){
        alert('有问题，请刷新页面重试！');
        return;
      }
      if(!$scope.sf.tpcFullName){
        alert('请填写公司全称');
        return;
      }
      if(!$scope.sf.tpcShortName){
        alert('请填写公司简称');
        return;
      }
      if(!$scope.sf.tpcAbbrLetter){
        alert('请填写拼音缩写');
        return;
      }else if($scope.sf.tpcAbbrLetter.length < 2){
        alert('拼音缩写长度必须大于两位');
        return;
      }
      if($scope.tpcCommoyType){
        var w = [];
        for(m in $scope.tpcCommoyType){
          if($scope.tpcCommoyType[m]){
            w.push(m);
          }
        }
        $scope.sf.tpcCompanyProperty = w.join(',');
        console.log($scope.sf.tpcCompanyProperty);
      }
      //return;
      faService.sanfangUpdate($scope.sf).then(function(json){
        $route.reload();
      });
    }
  }
}]);

faApp.controller('DownListCtrl', ['$scope','faService','$location','$controller','$route','exportService','$routeParams',function($scope,faService,$location,$controller,$route,exportService,$routeParams) {
  $controller('BaseListCtrl', {$scope: $scope});
  $scope.config = {
    "pageSize" : 20,
    "pageNo" : 1
  };
  $scope.isShowSaveUpload = false;
  $scope.uplpader = false;
  $scope.infoContent = false;
  $scope.isStartUpload = false;

  $scope.searchMap = {};
  $scope.search = function(notsave) {
      angular.forEach($scope.searchMap, function(o, i) {
        $scope.config[i] = (undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
      });
  }
  $scope.startUpload = function() {
    $scope.isStartUpload = true;
    faService.downLineUpFileload($scope.fileUrl).then(function(json){
      if(json.statusCode) {
        alert('出错了' + json.statusCode)
      }else{
        alert('导入成功');
        $scope.isShowSaveUpload = false;
        $scope.infoContent = false;
        $scope.isStartUpload = false;
        $route.reload();
      }
    })
}
  $scope.chkdownlineAll = function(){
    if($("#chkdownlineAll").attr("checked") == "checked"){
      $("[name='chkdownline']").attr("checked","checked");
    }else{
      $("[name='chkdownline']").attr("checked",false);
    }
  }
  $scope.delAll = function(){
    var allCheck = $("[name='chkdownline']");
    var ids = "";
    $("[name='chkdownline']").each(function(){
      if($(this).attr("checked") == "checked"){
          ids += $(this).val() + ",";
        }
    });
     if(ids.length > 0){
      if(!confirm("确认更新吗?")){
        return;
      }
      ids = ids.substring(0, ids.length - 1);
        var i={
          'ids':ids,
          'deleteTag':2
        };
      faService.downLineUpdata(i).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("删除成功！");
         $route.reload();
        }
      });
    }else{
      alert("请选择一个对象删除！");
    }
  }
  $scope.del = function(id) {
  var i={
    'id':id,
    'deleteTag':2
  };
  if(confirm("确认删除吗？")){
         faService.downLineUpdata(i).then(function(json){
        if(json.statusCode) {
          alert('删除失败' + json.statusCode)
        }else{
          alert('删除成功');
           $route.reload();
        }
      })
  }

  }
  $scope.$watch('config',function(){
    faService.downLineList($scope.config).then(function(json){ 
      $scope.list = json.list || [];
      $scope.pager = json.pager;
    });
  },true);

  $scope.onUploadFile({
    showMessage : function(m){ alert(m); },
    onUpload: function (fileName) {
      $scope.isShowSaveUpload = true;
      $scope.uplpader = true;
    },
    onComplete:function(f,response){
      if (response.statusCode == "0000") {
        $scope.uplpader = false;
        $scope.fileUrl = response.attribute.fileUrl;
        faService.downLineUpFile($scope.fileUrl).then(function(json){ 
          if(json.statusCode == '0003') {
            $scope.isShowSaveUpload = false;
            alert('上传文件无法识别，请按模板填写后重新上传')
          }else{
            $scope.isShowSaveUpload = true;
            $scope.infoContent = true;
            $scope.uploadList = json.list  || [];
          }
        });
      } else { 
        alert('上传文件无法识别，请按模板填写后重新上传'); 
      }
    }    
  });

}]);

faApp.controller('DownViewCtrl', ['$scope','faService','$location','$controller','$route','exportService','$routeParams', function($scope,faService,$location,$controller,$route,exportService,$routeParams) {
  $scope.id = $routeParams.id || '';
  $scope.edit = $routeParams.edit || false; //是否编辑
  $scope.item = {};
  $scope.showBlackAddFormFlag = false;

  if($scope.id) {
    faService.downLineDetail($scope.id).then(function(json){
      $scope.item = json.bean || [];
    })
  }
  $scope.save = function(){
    if($scope.form.$invalid){
      alert('请正确填写必填项（带*项）')
      return;
    }else if($scope.showBlackAddFormFlag){

      faService.downLineAdd($scope.item).then(function(json){
        if(json.statusCode) {
          alert('出错了' + json.statusCode)
        }else{
          alert('添加成功');
          $location.path('/fa/downline/list');
        }
      })
      $scope.showBlackAddFormFlag = false; 
    }else{
      $scope.showBlackAddFormFlag = true;
    }  
  }
  $scope.upData = function(){
    $scope.item.id = $scope.id;
    if($scope.form.$invalid){
      alert('请正确填写必填项（带*项）')
      return;
    }else{      
      faService.downLineUpdata($scope.item).then(function(json){
        if(json.statusCode) {
          alert('出错了' + json.statusCode)
        }else{
          alert('修改成功');
          $location.path('/fa/downline/list');
        }
      })     
    }
  }
}]);
faApp.controller('LcsmanlistCtrl', ['$scope','faService','$location','$controller','$route','exportService','licaishiManagerService','$routeParams', function($scope,faService,$location,$controller,$route,exportService,licaishiManagerService,$routeParams) {
   
    $controller('BaseListCtrl', {$scope: $scope});

    $scope.isShowDetail=false;

    $scope.config={
        "pageSize" : 50,
    "pageNo" : 1,
    };
    $scope.currentLoginId="";
    if($scope.loginStatus.loginName!='admin'){
      $scope.currentLoginId=$scope.loginStatus.id;
    }
    if(!$scope.config.systemUserId){
      $scope.config.systemUserId=$scope.currentLoginId;
    }
    $scope.item={};
    $scope.itemDetail={};
     $scope.$watch('config',function(){
      var c=$scope.config;
      if(c.endDate&&c.startDate&&c.endDate<c.startDate){
        alert("开始时间必须小于等于结束时间!");
        return;
      }
      if(c.endDate){
        if(c.endDate.length<18){//修改参数  避免多次调用  config变动
          c.endDate=c.endDate+" 23:59:59";
        }else{
          console.log("调用过了");
          return ;
        }
      }
      faService.lcsmanList(c).then(function(json){
        $scope.item = json.list || [];
      });
       faService.lcsmanDetailList(c).then(function(json){
        $scope.itemDetail = json.list || [];
        $scope.pager=json.pager;
      });
    },true);
   
    $scope.managerParam={"pageSize" : 10000};
    //如果是admin 查询全部
    if($scope.loginStatus.loginName=='admin'){
      licaishiManagerService.list($scope.managerParam).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $scope.licaishiManagerUserList = json.list;
            $scope.loading = false;
          }
        });
    }else{
       licaishiManagerService.otherList($scope.managerParam).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.licaishiManagerUserList = json.list;
          $scope.loading = false;
        }
      });
    }
   

    $scope.export = function(v){
      if(v==1){
        exportService.exportCSV($scope.config,"LCS_MAN_DETAIL_CSV");
        return ;
      }
      exportService.exportCSV($scope.config,"LCS_MAN_STATICTICS_CSV");
    };


  $scope.config.setPageSize = $scope.config.pageSize;
  $scope.changePageSize = function(){
      if(!$scope.config.setPageSize){
        alert('不为空且最大不超过1000');
        $scope.setPageSize = $scope.config.pageSize;
      }else{
        $scope.config.pageSize = $scope.config.setPageSize;
      }
    };
}]);

